package com.alexis.portknocking;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

// TODO: Use pause/resume/saved states for automatic DB saving

public class HostEdit extends Activity {
	private Long rowid;
    private DBAdapter dbadapter;
    private EditText wHost;
    private EditText wPort;
    private ImageButton wDeleteButton;
    
	private int activity_mode = DBAdapter.START_MODE;
	
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hostedit);
        this.setTitle("Add a host");
        
        dbadapter = new DBAdapter(this);
        dbadapter.open();
        
        wHost = (EditText)findViewById(R.id.EditText01);
        wPort = (EditText)findViewById(R.id.EditText02);
        
        wDeleteButton = (ImageButton)findViewById(R.id.ImageButton01);
        wDeleteButton.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View view) {
        		dbadapter.deleteHost(rowid);
        		
        		setResult(RESULT_OK);
        		finish();
        	}
        });
        
        Button savebutton = (Button)findViewById(R.id.Button01);
        savebutton.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View view) {
        		commit();
        		
        		setResult(RESULT_OK);
        		finish();
        	}
        });
        
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
        	activity_mode = extras.getInt(DBAdapter.KEY_STARTSTOP);
        	if (extras.containsKey(DBAdapter.KEY_ID)) {
            	rowid = extras.getLong(DBAdapter.KEY_ID);
        		populateFields();
        	}
        }
    }

	@SuppressWarnings("static-access")
	private void populateFields() {
		if (rowid != null) {
			wDeleteButton.setVisibility(wDeleteButton.VISIBLE);
			
			Cursor host = dbadapter.getRawHost(rowid);
			startManagingCursor(host);
			
			wPort.setText(String.valueOf(host.getInt(host.getColumnIndexOrThrow(DBAdapter.KEY_PORT))));
			wHost.setText(host.getString(host.getColumnIndexOrThrow(DBAdapter.KEY_HOST)));
		}
	}
	
	private void commit() {
		if (rowid == null) {
			dbadapter.createHost(wHost.getText().toString(), Long.valueOf(wPort.getText().toString()), activity_mode);
		} else {
			dbadapter.updateHost(rowid, wHost.getText().toString(), Long.valueOf(wPort.getText().toString()));
		}
	}
}
